package com.lx.screenshot.floatWindow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.lx.screenshot.R;
import com.lx.screenshot.databinding.ChooseAreaWindowBinding;
import com.lx.screenshot.util.SPUtil;
import com.lx.screenshot.util.SettingUtil;

public class ChooseAreaWindow extends FloatWindow {
    private ChooseAreaWindowBinding binding;
    private Bitmap bitmap;
    private float startX;
    private float startY;
    private Canvas canvas;
    private Paint paint;
    private float endX;
    private float endY;
    private int canvasW;
    private int canvasH;

    public ChooseAreaWindow(Context context) {
        super(context);
    }

    @Override
    protected void initParams() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        params.format = PixelFormat.RGBA_8888;
        params.gravity = Gravity.START;

        // 设置浮窗以外的触摸事件可以传递给后面的窗口、不自动获取焦点
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
    }

    @Override
    protected void initView() {
        floatWindow = new FrameLayout(context);
        binding = ChooseAreaWindowBinding.inflate(LayoutInflater.from(context), floatWindow, false);
        floatWindow.addView(
                binding.getRoot()
        );

        initCanvas();
    }

    /**
     * 初始化画布
     */
    private void initCanvas() {
        /* 获取屏幕宽高 */
        canvasW = floatWindow.getMeasuredWidth();
        canvasH = floatWindow.getMeasuredHeight();
        if (canvasW <= 0 || canvasH <= 0) {
            DisplayMetrics metrics = new DisplayMetrics();
            manage.getDefaultDisplay().getMetrics(metrics);
            canvasW = metrics.widthPixels;
            canvasH = metrics.heightPixels;
        }
        /* 创建画布 */
        bitmap = Bitmap.createBitmap(canvasW, canvasH, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
        canvas.drawColor(Color.parseColor("#4D000000"));
        /* 绘制文字 */
        if (!isDrag) {
            paint = new Paint();
            paint.setColor(Color.WHITE);
            paint.setTextSize(
                    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, context.getResources().getDisplayMetrics())
            );
            paint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText(
                    context.getText(R.string.chooseAreaWinTip).toString(),
                    canvasW / 2f, canvasH / 2f, paint
            );
            // 设置画笔为半透明，后面画透明矩形
            paint.setColor(Color.parseColor("#4D000000"));
        }
        binding.canvasIV.setImageBitmap(bitmap);
    }

    @Override
    protected void addClickListener() {
        floatWindow.setOnClickListener(v -> {
            destroy();
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void addTouchListener() {
        floatWindow.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX = event.getRawX();
                    startY = event.getRawY();
                    lastX = event.getX();
                    lastY = event.getY();
                    isDrag = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    initCanvas();
                    // 画一个透明矩形
                    bitmap = Bitmap.createBitmap(canvasW, canvasH, Bitmap.Config.ARGB_8888);
                    canvas = new Canvas(bitmap);
                    // 获取透明矩形的左上角的点和右下角的点
                    float l, t, r, b;
                    l = Math.min(lastX, event.getX());
                    t = Math.min(lastY, event.getY());
                    r = Math.max(lastX, event.getX());
                    b = Math.max(lastY, event.getY());
                    // 上
                    canvas.drawRect(0, 0, canvasW, t, paint);
                    // 下
                    canvas.drawRect(0, b, canvasW, canvasH, paint);
                    // 左
                    canvas.drawRect(0, t, l, b, paint);
                    // 右
                    canvas.drawRect(r, t, canvasW, b, paint);
                    binding.canvasIV.setImageBitmap(bitmap);
                    isDrag = true;
                    break;
                case MotionEvent.ACTION_UP:
                    // 有拖拽操作
                    if (isDrag) {
                        endX = event.getRawX();
                        endY = event.getRawY();

                        startResultWin(
                                Math.min(startX, endX),
                                Math.min(startY, endY),
                                Math.max(startX, endX),
                                Math.max(startY, endY)
                        );
                        SettingUtil.putSetting(context, "startX", String.valueOf(Math.min(startX, endX)));
                        SettingUtil.putSetting(context, "startY", String.valueOf(Math.min(startY, endY)));
                        SettingUtil.putSetting(context, "endX", String.valueOf(Math.max(startX, endX)));
                        SettingUtil.putSetting(context, "endY", String.valueOf(Math.max(startY, endY)));
                        SPUtil.put(context, SettingUtil.HAD_CHOOSE_AREA, true);

                        // 重置拖动标识为false
                        isDrag = false;
                        
                        // 销毁截屏悬浮窗
//                        destroy();
                    }
                    break;
            }

            return isDrag;
        });
    }
}
